﻿namespace EasyGo.Logic.Managers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using EasyGo.Common;
    using EasyGo.Common.Commands;
    using EasyGo.Logic.Model;

    public class CustomersManager : ICustomersManager
    {
        private readonly IRepository<Customer> customersRepository;

        public CustomersManager(IRepository<Customer> customersRepository)
        {
            this.customersRepository = customersRepository;
        }

        public void CreateCustomer(EditCustomerCommand command)
        {
            command.Validate();
            var entity = new Customer();
            entity.Description = command.Description;
            entity.Name = command.Name;
            entity.AddDate = DateTime.Now;
            Transaction.Execute(() => this.customersRepository.Create(entity));
        }

        public void EditCustomer(EditCustomerCommand command)
        {
            command.Validate();
            Transaction.Execute(() =>
            {
                var toEdit = customersRepository.Load(command.Id);
                if (toEdit != null)
                {
                    toEdit.Description = command.Description;
                    toEdit.Name = command.Name;

                    this.customersRepository.Update(toEdit);
                }
            });
        }

        public void DeleteCustomer(int id)
        {
            Transaction.Execute(() =>
            {
                var toDelete = customersRepository.Load(id);
                customersRepository.Delete(toDelete);
                customersRepository.SaveChanges();
            });
        }
    }
}
